<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>下拉列表的使用——选中多个</title>
</head>
<body>

<select name="fruits" id="fruits" multiple>
    <option value="苹果">苹果</option>
    <option value="香蕉">香蕉</option>
    <option value="橘子">橘子</option>
    <option value="西瓜">西瓜</option>
    <option value="草莓">草莓</option>
</select>
<label for="fruits"></label>


<div>你选中的水果是: <span>{{ fruit }}</span></div>

<script>
    let spanElement = document.querySelector("span");
    let fruit = null
    spanElement.innerText = eval(spanElement.innerText)


    let selectElement = document.querySelector("select");

    // console.log(selectElement);
    selectElement.addEventListener(
        "change",
        function () {
          /*  // console.log(selectElement.options.selectedIndex);
            let index = selectElement.options.selectedIndex;
            console.log(selectElement.options[index].value);
            fruit = selectElement.options[index].value
            // divElement.innerText = eval(divElement.innerText)
            spanElement.innerText = fruit*/

            fruit = []
            let selectedOptions = selectElement.selectedOptions;
            for (let i = 0; i < selectedOptions.length; i++) {
                fruit.push(selectedOptions[i].value)
                console.log(fruit);
                spanElement.innerText = fruit
            }

        }
    )


    // console.log(divElement);
</script>
</body>
</html>